const fs = require("fs");
const path = require("path");
const AppConfig = require("$config/app.config");
const db = require("@/db/mysql");
const BaseTaskScheduler = require("./base-task-scheduler");
const logger = require('$logger');
const fileBusinessService = require("../common/file-business.service");

// cron规则
const CRON_PATTERN = "*/20 * * * *";
const familyGroupStoreSizeTask = new BaseTaskScheduler();

const TaskHandler = async () => {
	try {
		logger.warning("定时任务执行中-同步家庭组的存储大小");
        const QUERY_GROUP_SQL = `SELECT id, name FROM family_group WHERE is_delete = 0`;
        const groupListResult = await db.query(QUERY_GROUP_SQL);
        if (groupListResult.code === 200 && groupListResult.results.length > 0) {
            const groupList = groupListResult.results;
            for (let i = 0; i < groupList.length; i++) {
                const { id, name } = groupList[i];
                logger.warning(`正在同步-[${name}]`);
                await fileBusinessService.syncFamilyGroupStoreSize(id);
                logger.warning(`同步-[${name}]完成`);
            }
        }
	} catch (error) {
		logger.error("定时同步家庭组的存储大小异常: ", error.message);
	}
};

// 创建一个30分钟执行一次的任务
familyGroupStoreSizeTask.createJob(CRON_PATTERN, TaskHandler, { initExecute: true });

module.exports = familyGroupStoreSizeTask;
